package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.MessageInfo;
import com.chexiehui.jc.mvp.mine.MessageListCovenant;
import com.chexiehui.jc.mvp.mine.MessageListPresenter;
import com.chexiehui.jc.utils.AppCommonUtil;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.LoadingLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 消息中心
 */
public class MessageListActivity extends BaseMvpActivity<MessageListPresenter> implements MessageListCovenant.View {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<MessageInfo> listData;
    private CommonAdapter<MessageInfo> listAdapter;
    private BasePage<MessageInfo> page;

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("消息中心");
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_message_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));
        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<MessageInfo>(mContext, R.layout.item_message_list, listData) {
            @Override
            protected void convert(ViewHolder holder, MessageInfo item, int position) {
                holder.setText(R.id.tv_item_time, AppCommonUtil.friendlyTime(item.getTime()));
                holder.setText(R.id.tv_item_title, new SpanUtils().append(item.getPushUserName())
                        .setFontSize(15, true)
                        .setForegroundColor(ContextCompat.getColor(mContext, R.color.c_333333))
                        .append(" ")
                        .append(item.getTitle()).setForegroundColor(ContextCompat.getColor(mContext, R.color.c_666666))
                        .setFontSize(13, true).create().toString());
                holder.setText(R.id.tv_item_content, item.getContent());
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                if(!StringUtils.isTrimEmpty(listData.get(position).getModuleID())){
                    switch (listData.get(position).getType()){
                        case 0:
                        case 3:
                        case 5:
                            startActivity(ForumDynamicDetailsActivity.class, new BundleBuilder()
                                    .putString("postId", listData.get(position).getModuleID())
                                    .create());
                            break;
                        case 1:
                            startActivity(ForumAppraiseDetailsActivity.class, new BundleBuilder()
                                    .putString("commentId", listData.get(position).getModuleID())
                                    .putString("postId", listData.get(position).getDynamicId())
                                    .create());
                            break;
                        case 2:
                            startActivity(SpecialCarDetailsActivity.class, new BundleBuilder()
                                    .putString("id", listData.get(position).getModuleID()).create());
                            break;
                    }
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);
        mvpPresenter.getList(1);
    }

    @Override
    protected MessageListPresenter createPresenter() {
        return new MessageListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<MessageInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh();
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

}
